<template>
  <div>
    <van-field
      readonly
      clickable
      :name="formItem.name"
      :value="formItem.value"
      :label="formItem.label"
      :placeholder="formItem.placeholder"
      @click="showCalendar = true"
    />
    <van-calendar :type="formItem.type" v-model="showCalendar" @confirm="onConfirm" />
  </div>
</template>

<script>
import Vue from "vue";
import { Calendar } from "vant";

Vue.use(Calendar);
export default {
  props: {
    formItem: {
      type: Object,
      default: {
        name: "",
        value: "",
        label: "",
        placeholder: "",
        type: "single"
      }
    }
  },
  data() {
    return {
      showCalendar: false
    };
  },
  methods: {
    formatDate(value) {
      //拼接日期
      let date = new Date(value);
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    delMultipeDate(values){//处理日期为multiple类型的数据
      let that = this;
      return values.map(item=>{
        return this.formatDate(item);
      });
    },
    filtersDate(date) {
      //根据日期类型处理数据
      switch (this.formItem.type) {
        case "single":
          return this.formatDate(date);
        case "multiple":
          return this.delMultipeDate(date);
        case "range":
          let [start, end] = date;
          return `${this.formatDate(start)} 至 ${this.formatDate(end)}`;
      }
    },
    onConfirm(date) {
      //获取日期
      this.formItem.value = this.filtersDate(date);
      this.show = false;
      this.showCalendar = false;
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
